#coding=utf-8
import pygtk
pygtk.require('2.0')

import random
import gtk
from stgui.guidb import *

from gtk import TreeView
import datetime
today = datetime.date.today().isoformat()

def cell_data_func(column, cell_renderer, model, iter_, user_data):
    
    col_index, col_attr = user_data
    v = model.get_value(iter_, col_index)
    
    tp = col_attr.pytype
    if tp == 'str':
        cell_renderer.set_property("text", v)
    elif tp == 'int': 
        cell_renderer.set_property("text", '%i'%v)
    elif tp == 'float':
        if col_attr.is_colored:
        
            cell_renderer.set_property("foreground-set",True)
            if(v > 0):
                cell_renderer.set_property('foreground',"red")
            else:
                cell_renderer.set_property('foreground',"green")
            
        if col_attr.is_percent:    
            cell_renderer.set_property("text", '%0.2f%%'%v)
        else:
            cell_renderer.set_property("text", '%0.2f'%v)   


class StListView(TreeView):
    
    def __init__(self, cols, data):
        
        self.colattrs = []
        for col in cols:
            self.colattrs.append(find_colattr(col))
        
        tps = [colattr.gtype.encode('u8') for colattr in self.colattrs]
        lt = gtk.ListStore(*tps)
        for d in data:
            lt.append(d)
        
        TreeView.__init__(self, lt) 
        
        i = 0
        for colattr in self.colattrs:
            #print i
            cell = gtk.CellRendererText()
            tc = gtk.TreeViewColumn(colattr.colhead, cell)
            
            tc.set_cell_data_func( cell, cell_data_func, (i, colattr))
            tc.set_sort_column_id(i)
            
            self.append_column(tc)
         
            i = i + 1
        
def get_testdata(date=None):
    if not date:
        date = today
        
    cols = ['date', 'name', 'code', 'close', 'change', 'trade_rate']
    
    cs = get_stcodes()
    ss = []
    for i in range(15):
        c = random.choice(cs)
        s = sess.query(Stock).filter_by(code=c).one()
        ss.append(s)
    
    data = []
    for s in ss:
        td = s.find_td(date)
        if not td:continue
        
        p = td.price
        d = [date, s.name, s.code, td.close, p.change, p.trade_rate]
        data.append(d)  
    
    return [cols, data]
            
if __name__ == '__main__':
    # example
    cols, data = get_testdata('2008-03-26')
    tv = StListView(cols, data)
    win = gtk.Window()
    win.add(tv)
    win.show_all()
    
    gtk.main()
    
